<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Contracts\Auth\Factory as Auth;

class AuthController extends Controller
{
    protected $jwt;
    protected $auth;

    public function __construct(JWTAuth $jwt,Auth $auth)
    {
        $this->jwt  = $jwt;
        $this->auth = $auth;
    }

    /**
     * 用户登录获取token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postLogin(Request $request)
    {
        if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
            return response()->json(['user_not_found'], 404);
        }

        return response()->json(compact('token'));
    }

    /**
     * 刷新token
     * @return \Illuminate\Http\JsonResponse
     * @throws AuthException
     */
    public function updateToken(Request $request){

        $this->auth->guard('api')->getToken()->refreshValidate();
        // 刷新token,获得新token
        $newToken = $this->auth->guard('api')->refreshToken();
        return response()->json(['token' => $newToken]);

//        try {
//
//            $old_token = $this->jwt->getToken();
//
//            $token = $this->jwt->refresh($old_token);
//
//            $this->jwt->invalidate($old_token);
//
//            $cacheKey = 'token';
//
//            Cache::forever($cacheKey,$token);
//
//        } catch (TokenExpiredException $e) {
//
//            throw new AuthException(
//
//                trans('errors.refresh_token_expired'), $e);
//
//        } catch (JWTException $e) {
//
//            throw new AuthException(
//
//                trans('errors.token_invalid'), $e);
//
//        }
//
//        return response()->json(compact('token'));
    }

    // 通过token获取用户信息
    public function getUser(Request $request) {
        return response()->json(['user' => $this->jwt->user()]);
    }
}
